import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    message,
} from 'antd';
import PageHeaderLayout from "../../../layouts/PageHeaderLayout";
import AdConfigruationList from "../../../components/Operation/AdConfigruation/AdConfigruationList";
import AdConfigruationAdd from "../../../components/Operation/AdConfigruation/AdConfigruationAdd";
import styles from './AdConfigruation.less';
import {powerControl} from '../../../utils/powerControl';
const AuthButton = powerControl(Button);

const FormItem = Form.Item;
const {Obtion}=Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');
@connect(state => ({
    rule: state.adConfigruation
}))
@Form.create()
export default class AdConfigruation extends PureComponent{
    state={
        modalVisible: false,
        editType: 'add',
        formValues: {},
        record: {},
        selectedRows: [],
    };

    componentDidMount(){
        const {dispatch} = this.props;
        dispatch({
            type: 'adConfigruation/fetch'
        });
    }

    handleSelectRows = (rows) =>{
      this.setState({
        selectedRow: rows
      });
    };

    /**
     * 改变表格里面的状态
     **/
    handleConfigruationListChange = (pagination, filtersArg, sorter) =>{
        const {dispatch} = this.props;
        const {formVales} = this.state;

        const filters = Object.keys(filtersArg).reduce((obj, key) =>{
            const newObj = {...obj};
            newObj[key] = getValue(filtersArg[key]);
            return newObj;
        }, {});

        const params = {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formVales,
            ...filters,
        };

        if (sorter.field){
            params.sorter = `${sorter.field}_${sorter.order}`;
        }

        dispatch({
            type: 'adConfigruation/fetch',
            payload: params,
        });
    };

    /**
     * 删除表格中的某一行
     **/
    handleDelConfigruationRow = (seat_id, pagination) => {
        const {dispatch} = this.props;
        dispatch({
            type: 'adConfigruation/del',
            payload: {seat_id: seat_id},
            callback: (response) => {
                if (response.result === 0){
                    message.success('删除成功');
                    this.handleModalSuccess(pagination)
                }else {
                    message.success('删除失败');
                }
            }

        });
    };

    /**
     * 编辑表格中的一行
     **/
    handleEditConfigruationRow = (record, pagination) =>{
        this.handleModalVisible(true);
        this.setState({
            editType: 'mod',
            record: record,
        });
    };

    /**
     * 新增成功重新查询
     * @param pagination
     */
    handleModalSuccess = (pagination) => {
        const {dispatch} = this.props;
        const {formValues} =this.state;
        const params={
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
            ...formValues
        };
        console.log("12132", params)
        dispatch({
           type: 'adConfigruation/fetch',
           payload: params
        });
    };

    /**
     * query
     */
    handleSearch = (e) =>{
        e.preventDefault();
        const {dispatch, form} = this.props;

        form.validateFields((err, fieldsValue) => {
            if (err){
                return;
            }
            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };
            this.setState({
                formValues: values,
            });

            dispatch({
                type: 'adConfigruation/fetch',
                payload: values,
            })
        });
    };

    /**
     * resetData
     */
    handleResetData = () =>{
        const {form, dispatch} = this.props;
        form.resetFields();
        dispatch({
            type: 'adConfigruation/fetch',
            payload: {},
        });
        this.setState({
            formValues: {},
        })
    };


    /**
     * 1.open.modal
     * 2.set.editType
     */
    handleVisibleModal = () =>{
        this.handleModalVisible(true);
        this.setState({
            editType: 'add'
        });

    };

    /**
     * add.adConfigruation
     */
    handleAddAdConfigruaion = () => {
        this.props.dispatch({
            type: 'adConfigruation/add',
            payload: {
                description: this.state.addInputValue,
            },
        });

        message.success('添加成功');
        this.setState({
            modalVisible:false,
        });
    };

    /**
     * modal.visible.state
     * @param flag
     */
    handleModalVisible = (flag) =>{
      this.setState({
          modalVisible: !!flag
      });
    };

    renderSimpleForm(){
        const {getFieldDecorator} = this.props.form;
        return(
           <Form layout="inline" onSubmit={this.handleSearch}>
               <Row gutter={{md: 8, lg: 24, xl: 48}}>
                   <Col md={8} sm={24}>
                       <FormItem label="位置编码">
                           {getFieldDecorator('seat_code')(
                               <Input placeholder="请输入"/>
                           )}
                       </FormItem>
                   </Col>

                   <Col md={8} sm={24}>
                       <FormItem label="位置类型">
                           {getFieldDecorator('seat_type')(
                               <Select placeholder="请选择" style={{width:'100%'}}>
                                   <Option value="">请选择</Option>
                                   <Option value="1">图片轮播</Option>
                                   <Option value="2">图片静态广告</Option>
                                   <Option value="3">列表</Option>
                               </Select>
                           )}
                       </FormItem>
                   </Col>
                   <Col md={8} sm={24}>
                       <span className={styles.sumbitButtons}>
                           <AuthButton auth="adConfigruation.search" type="primary" htmlType="submit">
                               查询
                           </AuthButton>
                           <AuthButton auth="adConfigruation.reset" style={{marginLeft: 8}} onClick={this.handleResetData}>
                               重置
                           </AuthButton>
                       </span>
                   </Col>
               </Row>
           </Form>
        );
    }

    renderForm(){
        return this.renderSimpleForm();
    }

    render(){
        const {modalVisible, editType, record, selectedRows} = this.state;
        const {rule: {loading: ruleLoading, data, adConfigruationList}} = this.props;
        return(
            <PageHeaderLayout
                title="广告推荐位置配置"
            >
                <Card bordered={false}>
                    <div className={styles.tableList}>
                        <div className={styles.tableListForm}>
                            {this.renderForm()}
                        </div>
                        <div className={styles.tableListOperator}>
                            <AuthButton
                                auth="adConfigruation.new"
                                type = "primary"
                                icon = "plus"
                                onClick={() => this.handleVisibleModal()}>
                                新建
                            </AuthButton>
                            <AdConfigruationList
                                selectedRows={selectedRows}
                                loading={ruleLoading}
                                data={data}
                                onSelectRow={this.handleSelectRows}
                                onChange={this.handleConfigruationListChange}
                                onDelRow={this.handleDelConfigruationRow}
                                onEditRow={this.handleEditConfigruationRow}
                            />
                        </div>
                    </div>
                </Card>
                <Modal
                    title="新增广告推荐位置配置"
                    visible={modalVisible}
                    onOk={this.handleAddAdConfigruaion}
                    onCancel={()=>this.handleModalVisible()}
                    footer={null}
                    key={new Date()}
                >
                    <AdConfigruationAdd
                        ref="adConfigruationAdd"
                        pagination={data.pagination}
                        editType={editType}
                        record={record}
                        categorySList={adConfigruationList}
                        handleModalVisible={this.handleModalVisible}
                        handleModalSuccess={this.handleModalSuccess}
                    />


                </Modal>

            </PageHeaderLayout>
        );
    }

}